import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { TinyPngCompressor } from './compressor';

export function activate(context: vscode.ExtensionContext) {
    console.log('TinyPNG Plus 扩展已激活');

    // 创建压缩器实例
    const compressor = new TinyPngCompressor();

    // 注册命令：使用 API 压缩
    const compressFolderCommand = vscode.commands.registerCommand(
        'tinypng.compressFolder',
        async (uri: vscode.Uri) => {
            if (uri && uri.fsPath) {
                await handleCompressFolder(uri.fsPath, 'api');
            } else {
                vscode.window.showErrorMessage('请在文件资源管理器中右键选择一个文件夹');
            }
        }
    );

    // 注册命令：使用爬虫压缩  
    const compressFolderCrawlerCommand = vscode.commands.registerCommand(
        'tinypng.compressFolderCrawler',
        async (uri: vscode.Uri) => {
            if (uri && uri.fsPath) {
                await handleCompressFolder(uri.fsPath, 'crawler');
            } else {
                vscode.window.showErrorMessage('请在文件资源管理器中右键选择一个文件夹');
            }
        }
    );

    // 注册命令：打开设置
    const openSettingsCommand = vscode.commands.registerCommand(
        'tinypng.openSettings',
        () => {
            vscode.commands.executeCommand('workbench.action.openSettings', 'tinypng');
        }
    );

    // 处理文件夹压缩的核心函数
    async function handleCompressFolder(folderPath: string, mode: 'api' | 'crawler') {
        // 检查文件夹是否存在
        if (!fs.existsSync(folderPath) || !fs.statSync(folderPath).isDirectory()) {
            vscode.window.showErrorMessage('选择的路径不是有效的文件夹');
            return;
        }

        // 获取配置
        const config = vscode.workspace.getConfiguration('tinypng');
        const apiKeys: string[] = config.get('apiKeys', []);
        const replaceOriginal: boolean = config.get('replaceOriginal', true);
        const outputFolder: string = config.get('outputFolder', 'compressed');
        const fileDelay: number = config.get('fileDelay', 200);
        const preserveStructure: boolean = config.get('preserveStructure', true);
        const copyUnsupported: boolean = config.get('copyUnsupported', true);
        const autoSwitchToCrawler: boolean = config.get('autoSwitchToCrawler', true);

        // 智能模式选择
        let finalMode = mode;
        if (mode === 'api' && (!apiKeys || apiKeys.length === 0 || apiKeys.every(key => !key.trim()))) {
            if (autoSwitchToCrawler) {
                finalMode = 'crawler';
                vscode.window.showInformationMessage('未配置有效的 API Key，自动切换到免费爬虫模式');
            } else {
                vscode.window.showErrorMessage('请先配置 TinyPNG API Key 或使用免费爬虫模式');
                return;
            }
        }

        // 确认操作
        const folderName = path.basename(folderPath);
        const modeText = finalMode === 'api' ? 'API 模式' : '免费爬虫模式';
        const replaceText = replaceOriginal ? '⚠️ 将直接替换原文件' : `输出到 ${outputFolder} 文件夹`;
        
        const confirmed = await vscode.window.showWarningMessage(
            `使用 ${modeText} 压缩文件夹 "${folderName}" 中的所有图片？\n${replaceText}`,
            { modal: true },
            '确认压缩',
            '取消'
        );

        if (confirmed !== '确认压缩') {
            return;
        }

        // 执行压缩
        try {
            await vscode.window.withProgress({
                location: vscode.ProgressLocation.Notification,
                title: `TinyPNG 压缩中 (${modeText})`,
                cancellable: false
            }, async (progress) => {
                const options = {
                    sourceRoot: folderPath,
                    apiKeys: finalMode === 'api' ? apiKeys : [],
                    replaceOriginal,
                    outputRoot: replaceOriginal ? '' : path.join(folderPath, outputFolder),
                    fileDelay,
                    preserveStructure,
                    copyUnsupported,
                    mode: finalMode,
                    progress: (current: number, total: number, message: string) => {
                        const percentage = Math.round((current / total) * 100);
                        progress.report({ 
                            increment: percentage,
                            message: `${message} (${current}/${total})`
                        });
                    }
                };

                const result = await compressor.compressFolder(options);
                
                // 显示结果
                const resultMessage = `✅ 压缩完成！\n` +
                    `成功: ${result.success} 张\n` +
                    `失败: ${result.failed} 张\n` +
                    `节省空间: ${result.savedSize} (${result.savedPercent}%)`;

                vscode.window.showInformationMessage(resultMessage);

                // 如果有失败的文件，询问是否重试
                if (result.failed > 0) {
                    const retryChoice = await vscode.window.showWarningMessage(
                        `有 ${result.failed} 张图片压缩失败，是否使用另一种模式重试？`,
                        '重试 (切换模式)',
                        '忽略'
                    );

                    if (retryChoice === '重试 (切换模式)') {
                        const retryMode = finalMode === 'api' ? 'crawler' : 'api';
                        await handleCompressFolder(folderPath, retryMode);
                    }
                }
            });

        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            vscode.window.showErrorMessage(`压缩失败: ${errorMessage}`);
            console.error('TinyPNG compression error:', error);
        }
    }

    // 订阅所有命令
    context.subscriptions.push(
        compressFolderCommand,
        compressFolderCrawlerCommand,
        openSettingsCommand
    );
}

export function deactivate() {
    console.log('TinyPNG Plus 扩展已停用');
}